from rest_framework import serializers
from account.models.user import User
from .role import RoleSerializer


class UserStandardSerializer(serializers.ModelSerializer):
    def to_representation(self, instance):
        data = super().to_representation(instance)
        user_roles = instance.user_roles.all().prefetch_related('role')
        roles, role_ids, permissions = [], [], []
        for user_role in user_roles:
            role = user_role.role
            role_ids.append(role.id)
            roles.append(RoleSerializer(role).data)
            permissions += role.permissions
        data['roles'] = roles
        data['role_ids'] = role_ids
        data['permissions'] = list(set(permissions))
        if instance.is_superuser:
            data['permissions'] = instance.get_permissions()
        return data

    class Meta:
        model = User
        fields = ['id', 'username', 'name']
